package com.itita.ww2.utils;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.smartfoxserver.v2.entities.data.ISFSArray;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSArray;
import com.smartfoxserver.v2.entities.data.SFSObject;

public class DataUtil {
	/**
	 * null值变为newValue,否则使用value
	 */
	public static final Object nullValueHandler(Object value, Object newValue) {
		return value == null ? newValue : value;
	}

	/**
	 * json转到bean去 obj
	 */
	public static final <T> T json2ObjBean(String json, TypeToken<T> typeOfT) {
		if (StringUtils.isBlank(json)) {
			json = "{}";
		}
		return new GsonBuilder().create().fromJson(json, typeOfT.getType());
	}

	/**
	 * json转到bean去 arr
	 */
	public static final <T> T json2ArrBean(String json, TypeToken<T> typeOfT) {
		if (StringUtils.isBlank(json)) {
			json = "[]";
		}
		return new GsonBuilder().create().fromJson(json, typeOfT.getType());
	}

	/**
	 * String 转为 int
	 * 若String为null或"",返回-1
	 */
	public static final int intValueOf(String val) {
		int result = -1;
		if (val != null && !val.equals("")) {
			result = Integer.valueOf(val);
		}
		return result;
	}

	/**
	 * String 转为 long
	 * 若String为null或"",返回-1
	 */
	public static final long longValueOf(String val) {
		long result = -1L;
		if (val != null && !val.equals("")) {
			result = Long.valueOf(val);
		}
		return result;
	}

	/**
	 * String 转为 ISFSObject
	 * 若String为null或"",返回空obj
	 */
	public static final ISFSObject objValueOf(String val) {
		ISFSObject obj = new SFSObject();
		if (val != null && !val.equals("")) {
			obj = SFSObject.newFromJsonData(val);
		}
		return obj;
	}

	/**
	 * 
	 * String 转为 ISFSArray
	 * 若String为null或"",返回空arr
	 */
	public static final ISFSArray arrValueOf(String val) {
		ISFSArray ret = SFSArray.newInstance();
		if (val != null && !val.equals("")) {
			ret = SFSArray.newFromJsonData(val);
		}
		return ret;
	}

	/**
	 * String 转为 DateTime
	 * 若不能转换则返回null
	 */
	public static final DateTime timeValueOf(String val) {
		if (val != null && !val.equals("")) {
			if (val.contains(".")) {
				val = val.substring(0, val.lastIndexOf("."));
			}
			DateTime ret = DateTime.parse(val, TimeUtil.redisTimestampFormatter);
			return ret.withZoneRetainFields(DateTimeZone.UTC);
		}
		return null;
	}

	public static final ISFSObject mergeSFSObject(ISFSObject... params) {
		ISFSObject ref = SFSObject.newInstance();
		for (ISFSObject obj : params) {
			for (String key : obj.getKeys()) {
				ref.put(key, obj.get(key));
			}
		}
		return ref;
	}
}
